//
//  HomeViewController.m
//  MoneyLog
//
//  Created by wicresoft on 5/16/11.
//  Copyright 2011 wicresoft. All rights reserved.
//

#import "HomeViewController.h"
#import "RecordListViewController.h"
#import "RecordViewController.h"
#import "RecordWrapper.h"

#import "MyController.h"

extern NSString *kSectionTitleKey;
extern NSString *kRowViewKey;
extern NSString *kRowTextKey;

@implementation StatResult
@synthesize incomeValue;
@synthesize incomeCount;
@synthesize expenseValue;
@synthesize totalValue;
@synthesize expenseCount;
@synthesize totalCount;

-(void)resetData {
    self.incomeValue = 0;
    self.incomeCount = 0;
    self.expenseValue = 0;
    self.expenseCount = 0;
    self.totalValue = 0;
    self.totalCount = 0;
}

@end


@implementation HomeViewController
@synthesize _tableView;
@synthesize dataSourceArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [_tableView release];
    [dataSourceArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"主界面";
    
    self.dataSourceArray = [NSArray arrayWithObjects:
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             [self titleForSection:0], kSectionTitleKey,
                             [self viewForTableRow:[NSIndexPath indexPathForRow:0 inSection:kDaySection]], kRowViewKey,
                             [self textForTableRow:[NSIndexPath indexPathForRow:1 inSection:kDaySection]], kRowTextKey,
							 nil],
							
							[NSDictionary dictionaryWithObjectsAndKeys:
                             [self titleForSection:1], kSectionTitleKey,
                             [self viewForTableRow:[NSIndexPath indexPathForRow:0 inSection:kMonthSection]], kRowViewKey,
                             [self textForTableRow:[NSIndexPath indexPathForRow:1 inSection:kMonthSection]], kRowTextKey,
							 nil],
							
							[NSDictionary dictionaryWithObjectsAndKeys:
                             [self titleForSection:2], kSectionTitleKey,
                             [self viewForTableRow:[NSIndexPath indexPathForRow:0 inSection:kYearSection]], kRowViewKey,
                             [self textForTableRow:[NSIndexPath indexPathForRow:1 inSection:kYearSection]], kRowTextKey,
							 nil],							
							nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.toolbarHidden = YES;
    self.dataSourceArray = [NSArray arrayWithObjects:
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             [self titleForSection:0], kSectionTitleKey,
                             [self viewForTableRow:[NSIndexPath indexPathForRow:0 inSection:kDaySection]], kRowViewKey,
                             [self textForTableRow:[NSIndexPath indexPathForRow:1 inSection:kDaySection]], kRowTextKey,
							 nil],
							
							[NSDictionary dictionaryWithObjectsAndKeys:
                             [self titleForSection:1], kSectionTitleKey,
                             [self viewForTableRow:[NSIndexPath indexPathForRow:0 inSection:kMonthSection]], kRowViewKey,
                             [self textForTableRow:[NSIndexPath indexPathForRow:1 inSection:kMonthSection]], kRowTextKey,
							 nil],
							
							[NSDictionary dictionaryWithObjectsAndKeys:
                             [self titleForSection:2], kSectionTitleKey,
                             [self viewForTableRow:[NSIndexPath indexPathForRow:0 inSection:kYearSection]], kRowViewKey,
                             [self textForTableRow:[NSIndexPath indexPathForRow:1 inSection:kYearSection]], kRowTextKey,
							 nil],							
							nil];
    [self._tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;//(interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - * Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   return ([indexPath row] == 0) ? 50.0 : 22.0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[self.dataSourceArray objectAtIndex:section] objectForKey:kSectionTitleKey];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    NSString *title = nil;
	
	return title;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return [self.dataSourceArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    if (indexPath.row == 0) {
        UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        detailButton.frame = CGRectMake(270, 10, 25, 25);
        detailButton.backgroundColor = [UIColor clearColor];
        [detailButton addTarget:self action:@selector(detailAction:) forControlEvents:UIControlEventTouchUpInside];
        [detailButton setTag:indexPath.section];
        [cell addSubview:detailButton];
        
        if (indexPath.section ==0) {
            UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
            addButton.frame = CGRectMake(16, 10, 25, 25);
            addButton.backgroundColor = [UIColor clearColor];
            [addButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:addButton];
        }
        
        for (UIView *view in [cell.contentView subviews]) {
            [view removeFromSuperview];
        }
        
        [cell.contentView addSubview:[[dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowViewKey]];
    }
    else {
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.textLabel.font = [UIFont systemFontOfSize:12.0];
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.text = [[dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowTextKey];
    }
        
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
    
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - * Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - * Actions

- (NSString *)titleForSection:(NSInteger)section
{
    NSDate *date = [NSDate new];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    switch (section)
    {
        case kDaySection: 
        {
            [dateFormatter setDateFormat:@"今天 yyyy-MM-dd"];
            NSString *dateString = [dateFormatter stringFromDate:date];
            
            return dateString; 
        }
        case kMonthSection:
        {
            [dateFormatter setDateFormat:@"本月 yyyy-MM"];
            NSString *dateString = [dateFormatter stringFromDate:date];
            
            return dateString; 
        }
        case kYearSection:
        {
            [dateFormatter setDateFormat:@"今年 yyyy"];
            NSString *dateString = [dateFormatter stringFromDate:date];
            
            return dateString;  
        }
    }
    [dateFormatter release];
    
    return nil;
}

- (id)viewForTableRow:(NSIndexPath *)indexPath
{
    UIView *view = [[[UIView alloc] init] autorelease];
    
    int year,month,day;
    NSDate *date = [NSDate new];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
	year = [dateComponents year];
    month = [dateComponents month];
	day = [dateComponents day];
	[calendar release];
    
    UILabel *incomeLable = [[UILabel alloc] initWithFrame:CGRectMake(32, 4, 100, 20)];
    incomeLable.textColor = [UIColor blueColor];
    incomeLable.font = [UIFont systemFontOfSize:12];
    //incomeLable.textAlignment = UITextAlignmentCenter;
    
    UILabel *expenseLable = [[UILabel alloc] initWithFrame:CGRectMake(32, 24, 100, 20)];
    expenseLable.textColor = [UIColor purpleColor];
    expenseLable.font = [UIFont systemFontOfSize:12];
    //expenseLable.textAlignment = UITextAlignmentCenter;
    
    UILabel *totalLable = [[UILabel alloc] initWithFrame:CGRectMake(160, 4, 100, 42)];
    totalLable.font = [UIFont systemFontOfSize:16];
    //totalLable.textAlignment = UITextAlignmentCenter;
    
    StatResult *statResult;
    switch (indexPath.section) {
        case kDaySection:
        {
            statResult =[self statRecord:[NSString stringWithFormat:@" year=%d and month=%d and day=%d",year,month,day]];
            
            incomeLable.text = [NSString stringWithFormat:@"+￥:%.2f",statResult.incomeValue];
            [view addSubview:incomeLable];
            
            expenseLable.text = [NSString stringWithFormat:@" -￥:%.2f",statResult.expenseValue];
            [view addSubview:expenseLable];
            
            NSString *textString;
            if (statResult.totalValue>=0) {
                totalLable.textColor = [UIColor blueColor];
                textString = [NSString stringWithFormat:@"+￥:%.2f",statResult.totalValue];
            }
            else {
                totalLable.textColor = [UIColor purpleColor];
                textString = [NSString stringWithFormat:@" -￥:%.2f",statResult.totalValue];
            }
            
            totalLable.text = textString;
            [view addSubview:totalLable];
            
            break;
        }
        case kMonthSection:
        {
            statResult =[self statRecord:[NSString stringWithFormat:@" year=%d and month=%d",year,month]];
            
            incomeLable.text = [NSString stringWithFormat:@"+￥:%.2f",statResult.incomeValue];
            [view addSubview:incomeLable];
            
            expenseLable.text = [NSString stringWithFormat:@" -￥:%.2f",statResult.expenseValue];
            [view addSubview:expenseLable];
            
            NSString *textString;
            if (statResult.totalValue>=0) {
                totalLable.textColor = [UIColor blueColor];
                textString = [NSString stringWithFormat:@"+￥:%.2f",statResult.totalValue];
            }
            else {
                totalLable.textColor = [UIColor purpleColor];
                textString = [NSString stringWithFormat:@" -￥:%.2f",statResult.totalValue];
            }
            
            totalLable.text = textString;
            [view addSubview:totalLable];

            break;
        }
        case kYearSection:
        {
            statResult =[self statRecord:[NSString stringWithFormat:@" year=%d",year]];
            
            incomeLable.text = [NSString stringWithFormat:@"+￥:%.2f",statResult.incomeValue];
            [view addSubview:incomeLable];
            
            expenseLable.text = [NSString stringWithFormat:@" -￥:%.2f",statResult.expenseValue];
            [view addSubview:expenseLable];
            
            NSString *textString;
            if (statResult.totalValue>=0) {
                totalLable.textColor = [UIColor blueColor];
                textString = [NSString stringWithFormat:@"+￥:%.2f",statResult.totalValue];
            }
            else {
                totalLable.textColor = [UIColor purpleColor];
                textString = [NSString stringWithFormat:@" -￥:%.2f",statResult.totalValue];
            }
            
            totalLable.text = textString;
            [view addSubview:totalLable];

            break;
        }
        default:
            break;
    }
    
    [incomeLable release];
    [expenseLable release];
    [totalLable release];
    
    return view;
}

- (NSString *)textForTableRow:(NSIndexPath *)indexPath
{
    int year,month,day;
    NSDate *date = [NSDate new];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
	year = [dateComponents year];
    month = [dateComponents month];
	day = [dateComponents day];
	[calendar release];
        
    NSString *textString;
    StatResult *statResult;
    switch (indexPath.section) {
        case kDaySection:
        {
            statResult =[self statRecord:[NSString stringWithFormat:@" year=%d and month=%d and day=%d",year,month,day]];
            textString =[NSString stringWithFormat:@"收入: %d条    支出: %d条     合计: %d条",statResult.incomeCount,statResult.expenseCount,statResult.totalCount];
            break;
        }
        case kMonthSection:
        {
            statResult =[self statRecord:[NSString stringWithFormat:@" year=%d and month=%d",year,month]];
            textString =[NSString stringWithFormat:@"收入: %d条    支出: %d条     合计: %d条",statResult.incomeCount,statResult.expenseCount,statResult.totalCount];
            break;
        }
        case kYearSection:
        {
            statResult =[self statRecord:[NSString stringWithFormat:@" year=%d",year]];
            textString =[NSString stringWithFormat:@"收入: %d条    支出: %d条     合计: %d条",statResult.incomeCount,statResult.expenseCount,statResult.totalCount];
            break;
        }
        default:
            break;
    }
    
    return textString;
}

-(void)addAction{
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc] 
                               initWithTitle:@"返回" 
                               style:UIBarButtonItemStyleBordered 
                               target:nil 
                               action:nil];
    
    RecordViewController *controller =[[RecordViewController alloc] initWithStyle:UITableViewStyleGrouped];
    controller.titleString=@"添加记录";
    controller.viewMode=0;
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:controller];
    navigation.navigationItem.backBarButtonItem = backItem;
    [self.navigationController presentModalViewController:navigation animated:YES];
    [navigation release];
    [backItem release];
    [controller release];
}

-(void)detailAction:(id)sender{
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc] 
                               initWithTitle:@"返回" 
                               style:UIBarButtonItemStyleBordered 
                               target:nil 
                               action:nil];
    
    RecordListViewController *controller =[[RecordListViewController alloc] init];
    controller.searchMode = [sender tag];
    controller.searchDate = [NSDate new];
    controller.hidesBottomBarWhenPushed = YES;
    self.navigationItem.backBarButtonItem = backItem;
    [self.navigationController pushViewController:controller animated:YES];
    [backItem release];
    [controller release];
}

-(StatResult *)statRecord:(NSString *)whereString
{
    StatResult *statResult = [[[StatResult alloc] init] autorelease];
    NSMutableArray *arrary = [g_Database getRecordArray:whereString];
    
    statResult.totalCount = [arrary count];
    for (RecordWrapper *record in arrary) {
        if ([record.type isEqualToString:@"收入"]) {
            statResult.incomeCount++;
            statResult.incomeValue += record.money;
            statResult.totalValue += record.money;
        }
        else
        {
            statResult.expenseCount++;
            statResult.expenseValue += record.money;
            statResult.totalValue -= record.money;
        }
    }
    
    return statResult;
}

@end
